﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using game.tool;

namespace game.LoadScene
{
    public class SceneLoader : Singleton<SceneLoader>
    {
        static bool stepFin = false;
        AsyncOperation _ao;
        new string name;
        public SceneLoadingMask mask;
        public Text textC;
        public Slider sli;
        bool isLoading = false;
        private void Start()
        {
            DontDestroyOnLoad(gameObject);
        }
        public static void LoadScene(string _name)
        {
            if (Instance == null)
            {
                return;
            }
            Instance.StartCoroutine(Instance.DoLoadScene(_name));
        }
        IEnumerator DoLoadScene(string _name)
        {
            stepFin = false;
            name = _name;
             _ao = SceneManager.LoadSceneAsync(_name);

            while (!stepFin)
            {
                yield return null;
            }
            // 去掉 mask
            stepFin = false;
            if (mask != null)
            {
                mask.HideMask(() => stepFin = true);
            }
            while (!stepFin)
            {
                yield return null;
            }
            Debug.Log("Loading!!!");
            OnSceneReady();  
        }
        public static void OnSceneConstructorFinish()
        {
            stepFin = true;
        }

        void Update()
        {
            if (_ao != null)
            {
                textC.text = "Loading Scene:" + name + "--" + (_ao.progress * 100f).ToString() + "%";
                sli.value = _ao.progress;
            }
        }


        void OnSceneReady()
        {
            Destroy(gameObject);
        }
    }
}

